<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Controller;
use think\Config;
use addons\third\model\Third;
use app\api\controller\Wechat;
use addons\third\library\Service;
use app\common\library\Auth;
/**
 * 微信授权接口
 */
class Wxopera extends api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 2;
    }  

    /**
     * 网页授权
     */
    public function shouquan(){
     
     $wx = new Wechat();
     $APPID = $wx->APPID;
     $redirect = urlencode("http://hanluojie.znwlsz.com/api/Wxopera/callback");

    // 调起微信授权提示
     $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$APPID."&redirect_uri=".$redirect."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    // 跳转授权页面
    header("location:$url");
    // $this->redirect($url);
    }
    /**
    * 网页授权的回调
    */
    public function callback(){
     
     // 一、获取用户授权回调里的code  code只有五分钟有效
    // echo "<pre>";
     // 获取当前url的参数部分
    $params = $_SERVER["QUERY_STRING"];    // s=/index/Wxopera/callback&code=code&state=STATE
     // 拆分成数组
    $arr = explode('&',$params);
    $code = explode('=',$arr[1]);
    $code = $code[1];

    $res = $this->get_token_openid($code);

    // 三、获取用户信息
    $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN";

    $wx = new Wechat();
    $userinfo = $wx->http_curl($url2);
    // array(9) {
    //   ["openid"] => string(28) "oo37h5_wHvmdAexX5keGa7QjW0Xg"
    //   ["nickname"] => string(5) "Vicky"
    //   ["sex"] => int(1)
    //   ["language"] => string(5) "zh_CN"
    //   ["city"] => string(6) "广州"
    //   ["province"] => string(6) "广东"
    //   ["country"] => string(6) "中国"
    //   ["headimgurl"] => string(131) "http://thirdwx.qlogo.cn/mmopen/vi_32/3keV6zIaF9bBy1ibJKykMcn7hnbxydkQGPnVdFlibLlGUyhgXyuiaFdgYDNOgyqS2ZMjZMbZ7e6UibtxkdUOAMBc5Q/132"
    //   ["privilege"] => array(0) {
    //   }
    // }

    $platform = 'wx';

    $result = $userinfo;
    $result['access_token'] = $res['access_token'];
    
    // 第三方登录入库
    // 在user表创建一条新用户数据
    $ret = Service::connect($platform, $result);

    if ($ret) {
        //登录成功后的用户数据操作
        $auth = Auth::instance();

        $this->success("登录成功", ['openid'=>$userinfo['openid'],'token' => $auth->getUserinfo()['token']]);
    } else {
        $this->error("连接失败");
    }
    }
    protected function curl_url($url, $json)
    { 
        $body = json_encode($json);
        // return $body;
        $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
        // 二、通过code获取网页授权access_token 有效期7200s,过期需要重新获取，这里暂不处理过期的问题
    
    protected function get_token_openid($code){

        //当前时间戳
        $now_time = time();

        //失效时间
        $timeout = 7200 ;

        //判断access_token是否过期
        $before_time = $now_time - $timeout;

        //未查找到就为过期
        $access_token = Db::name('token_openid')
        ->where('createtime' ,'>',$before_time)
        ->find();

        if(empty($access_token)){
        $config = get_addon_config('third');

        $appId= $config['wechat']['app_id'];// 小程序 APPID
        $appSecret = $config['wechat']['app_secret'];//小程序密钥
        
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
        $wx = new Wechat();
        $res = $wx->http_curl($url);
        Db::name('token_openid')->insert(['access_token'=>$res['access_token'],'createtime'=>$now_time,'openid'=>$res['openid']]);
        return $res;
        }
        return $access_token;
    }

    
    

  

}
